package com.farshine.baokan.box;

public class MakeCommand {
    public static class BoxCommand {
        public byte addr;
        public CommandTyep command;
        public byte[] data;
    }

    public byte[] make(CommandTyep commandTyep, int addr, byte[] data) {
        if (data==null) return null;
        //0x26(&)、地址、命令位、数据长度、数据、校验位、0x0D
        byte[] buf = new byte[12 + data.length];
        buf[0] = 0x26;
        buf[1] = (byte)(0x40 + (addr & 0x0F));
        buf[2] = (byte)(0x40 + ((addr>>4) & 0x0F));
        int command = commandTyep.getNumber();
        buf[3] = (byte)(0x40 + (command & 0x0F));
        buf[4] = (byte)(0x40 + ((command>>4) & 0x0F));
        int len = data.length;
        buf[5] = (byte)(0x40 + (len & 0x0F));
        buf[6] = (byte)(0x40 + ((len>>4) & 0x0F));
        buf[7] = (byte)(0x40 + ((len>>8) & 0x0F));
        buf[8] = (byte)(0x40 + ((len>>12) & 0x0F));
        //复制数据
        if (len>0)
            System.arraycopy(data, 0, buf, 9, len);
        //校验
        byte xor = 0;
        for (int i=1;i<len+9;i++) {
            xor ^= buf[i];
        }
        buf[9+len]   = (byte)(0x40 + ((xor) & 0x0F));
        buf[9+len+1] = (byte)(0x40 + ((xor>>4) & 0x0F));
        buf[9+len+2] = 0x0D;

        return buf;
    }

    public BoxCommand parse(byte[] data) {
        BoxCommand boxCommand = new BoxCommand();
        boxCommand.command = CommandTyep.None;

        if (data == null || data.length<12 || data[0]!=0x3E || data[data.length-1]!=0x0D) {
            //数据不正确
            return boxCommand;
        }
        int len = ((data[5]&0x0F) | ((data[6]&0x0F)<<4) | ((data[7]&0x0F)<<8) | ((data[8]&0x0F)<<12));
        if (len+12 != data.length) {
            //长度不对
            return boxCommand;
        }
        boxCommand.addr = (byte)((data[1]&0x0F) | ((data[2]&0x0F)<<4));
        int command = ((data[3]&0x0F) | ((data[4]&0x0F)<<4));
        boxCommand.command = CommandTyep.fromIndex(command);
        boxCommand.data = new byte[len];
        System.arraycopy(data, 9, boxCommand.data, 0, len);

        return boxCommand;
    }
}
